import {
  createRouter,
  createWebHistory,
  type NavigationGuardNext,
  type RouteLocationNormalized,
  type RouteRecordRaw,
} from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "登录",
    component: () => import("@/views/Login/index.vue"),
  },
  {
    path: "/",
    name: "首页",
    meta: { requiresAuth: true }, // 添加路由元信息
    component: () => import("@/views/Page/index.vue"),
    redirect: "/home",
    children: [
      {
        path: "home",
        name: "Home",
        component: () => import("@/views/Home/index.vue"),
      },
      {
        path: "profile",
        name: "Profile",
        component: () => import("@/views/Profile/index.vue"),
      },
      {
        path: "setting",
        name: "Setting",
        component: () => import("@/views/Profile/setting.vue"),
      },
      {
        path: "security",
        name: "Security",
        component: () => import("@/views/Profile/security.vue"),
      },
      {
        path: "account",
        name: "Account",
        component: () => import("@/views/Profile/account.vue"),
      },
      {
        path: "demo",
        name: "Demo",
        component: () => import("@/views/Demo/svgIndex.vue"),
      },
      {
        path: "svgLoading",
        name: "SvgLoading",
        component: () => import("@/views/Demo/svgIndex.vue"),
      },
      {
        path: "diyForm",
        name: "DiyForm",
        component: () => import("@/views/Demo/diyFormIndex.vue"),
      },
      {
        path: "/waterfall",
        name: "Waterfall",
        component: () => import("@/views/Demo/waterfall.vue"),
      },

      {
        path: "/mobileVue",
        name: "MobileVue",
        component: () => import("@/views/Demo/mobileVue.vue"),
      },
      {
        path: "/project",
        name: "Project",
        component: () => import("@/views/Projects/index.vue"),
      },
      {
        path: "/bootstrap",
        name: "Bootstrap",
        component: () => import("@/views/Bootstrap/index.vue"),
      },
      {
        path: "/chats",
        name: "Chats",
        component: () => import("@/views/Chat/index.vue"),
      },
    ],
  },

  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/NotFound.vue"),
    meta: {
      title: "404页面",
    },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  const isAuthenticated = localStorage.getItem("token");

  // 如果访问的是登录页且已登录，重定向到首页
  if (to.path === "/login" && isAuthenticated) {
    return next("/");
  }

  // 如果访问的是需要认证的页面且未登录
  if (to.matched.some((record) => record.meta.requiresAuth) && !isAuthenticated) {
    return next({
      path: "/login",
      query: { redirect: to.fullPath },
    });
  }

  if (!to.matched.length) {
    next({ name: "NotFound" });
  }

  next();
});

export default router;
